package com.order.web.action;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.hibernate.type.StringType;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.order.dao.jdbcDao;
import com.order.domain.Contact;
import com.order.domain.Customer;
import com.order.domain.PageBean;
import com.order.service.IContactService;
import com.order.service.ICustomerService;
import com.order.service.IUserService;

import net.sf.json.JSONObject;

import com.order.domain.User;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

/**
 * 学生的动作类
 * 
 * @author zhy
 *
 */
@Controller("customerAction")
@Scope("prototype")
@ParentPackage("struts-default") // struts-default crm
@Namespace("/customer")
@Results({ 
		@Result(name = "addUI", type = "dispatcher", location = "/jsp/customer/add.jsp"),
		// @Result(name = "findAll", type = "dispatcher", location ="/jsp/customer/list.jsp"),
		@Result(name = "json", type = "dispatcher", location = "/jsp/customer/list1.jsp"),
		@Result(name = "listCustomer", type = "redirectAction", location = "findAllCustomer"),
		@Result(name = "editUI", type = "dispatcher", location = "/jsp/customer/edit.jsp"),
		@Result(name = "contactfindall", type = "dispatcher", location = "/jsp/customer/contact.jsp"),
		@Result(name = "editUIcontact", type = "dispatcher", location = "/jsp/customer/contactedit.jsp"),
		@Result(name = "listContact", type = "redirectAction", location = "contact"),
		@Result(name = "findCommon", type = "dispatcher", location = "/jsp/customer/common.jsp"),
		@Result(name = "pullCommon", type = "redirectAction", location = "common"),
		@Result(name = "putCommon", type = "redirectAction", location = "findAllCustomer"),
		@Result(name = "contactRoot", type = "dispatcher", location = "/jsp/customer/contactRoot.jsp") 
})
public class CustomerAction extends ActionSupport implements ModelDriven<Customer>, ServletResponseAware, ServletRequestAware {

	private static final long serialVersionUID = 1L;
	private Customer customer = new Customer();
	private List<Customer> customers;
	private List<User> affiliatedTeachers;
	private List<User> users;
	private List<Contact> contacts;

	// 条件搜索容器
	private String select;

	// 设置页面最大记录数
	int pageSize = 5;

	// 使用属性驱动接收pageNumber即可
	private int currentPage = 1;

	// 今日联系总人数
	private int countContact = 0;

	// 批量删除id
	private String checkTnum;

	// 实时修改容器
	private String str;

	// switch值
	private int n;

	String jsonStr;

	private HttpServletResponse response;
	private HttpServletRequest request;

	@Resource(name = "customerService")
	private ICustomerService customerService;

	@Resource(name = "contactService")
	private IContactService contactService;

	@Resource(name = "userService")
	private IUserService userService;

	@Override
	public Customer getModel() {
		// System.out.println("模型驱动调用getModel方法："+customer.hashCode());
		return customer;
	}

	/**
	 * 编辑学生
	 * 
	 * @return
	 */
	@Action("editCustomer")
	public String editCustomer() {

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject jsonCustomer;

		if (customer.getStudentId() == null) {
			map.put("ok", false);
			map.put("err", "请选择要修改的学生");

			jsonCustomer = JSONObject.fromObject(map);
			jsonStr = jsonCustomer.toString();

			// 添加response响应头
			crossDomain();
			return "json";
		}

		// 将下次联系时间设置为" "
		User u = customer.getAffiliatedTeacher();
		int uId = u.getUserId();
		if (uId == 0) {
			customer.setNextDate("");
		}

		// 联系总人数 - 1 防重复操作
		calculationContactNumberReduce(customer.getStudentId(), customer.getNextDate());

		customerService.updateCustomer(customer);

		// 计算今日联系总人数
		calculationContactNumber(customer);

		map.put("ok", true);
		jsonCustomer = JSONObject.fromObject(map);
		jsonStr = jsonCustomer.toString();

		// 添加response响应头
		crossDomain();
		return "json";
		// return "listCustomer";
	}

	/**
	 * 实时修改
	 * 
	 * @return
	 */
	@Action("instantaneousEdit")
	public String instantaneousEdit() {

		int num = getN();
		int i;

		Customer c = customerService.findCustomerById(customer.getStudentId());
		Map<String, Object> map = new HashMap<String, Object>();

		switch (num) {

		case 1: // studentName
			c.setStudentName(getStr());
			map.put("ok", true);
			break;
		case 2: // studentSex
			i = Integer.parseInt(getStr());
			c.setStudentSex(i);
			map.put("ok", true);
			break;
		case 3: // studentAge
			i = Integer.parseInt(getStr());
			c.setStudentAge(i);
			map.put("ok", true);
			break;
		case 4: // phone1
			long l1 = Long.parseLong(getStr());
			c.setPhone1(l1);
			map.put("ok", true);
			break;
		case 5: // phone2
			long l2 = Long.parseLong(getStr());
			c.setPhone2(l2);
			map.put("ok", true);
			break;
		case 6: // nextDate
			// 将下次联系时间设置为" "
			User u = c.getAffiliatedTeacher();
			int uId = u.getUserId();
			if (uId == 0) {
				c.setNextDate("");
			} else {
				c.setNextDate(getStr());
			}

			// 联系总人数 - 1 防重复操作
			calculationContactNumberReduce(customer.getStudentId(), getStr());
			map.put("ok", true);
			break;
		case 7: // address
			c.setAddress(getStr());
			map.put("ok", true);
			break;
		case 8: // remark
			c.setRemark(getStr());
			map.put("ok", true);
			break;
		case 9: // followUp
			c.setFollowUp(getStr());
			map.put("ok", true);
			break;

		default:
			map.put("ok", false);
			map.put("err", "修改失败，未获取到switch case值！");
			break;
		}

		customerService.updateCustomer(c);

		if (num == 6) {
			// 计算今日联系总人数
			calculationContactNumber(c);
		}

		JSONObject jsonObject = JSONObject.fromObject(map);
		jsonStr = jsonObject.toString();

		// 添加response响应头
		crossDomain();
		return "json";
		// return "listCustomer";
	}

	/**
	 * 今日联系实时修改
	 * 
	 * @return
	 */
	@Action("instantaneousContactEdit")
	public String instantaneousContactEdit() {

		int num = getN();
		int i;

		Customer c = customerService.findCustomerById(customer.getStudentId());
		Map<String, Object> map = new HashMap<String, Object>();

		switch (num) {

		case 1: // studentName
			c.setStudentName(getStr());
			map.put("ok", true);
			break;
		case 2: // studentSex
			i = Integer.parseInt(getStr());
			c.setStudentSex(i);
			map.put("ok", true);
			break;
		case 3: // studentAge
			i = Integer.parseInt(getStr());
			c.setStudentAge(i);
			map.put("ok", true);
			break;
		case 4: // phone1
			long l1 = Long.parseLong(getStr());
			c.setPhone1(l1);
			map.put("ok", true);
			break;
		case 5: // phone2
			long l2 = Long.parseLong(getStr());
			c.setPhone2(l2);
			map.put("ok", true);
			break;
		case 6: // nextDate
			// 将下次联系时间设置为" "
			User u = c.getAffiliatedTeacher();
			int uId = u.getUserId();
			if (uId == 0) {
				c.setNextDate("");
			} else {
				c.setNextDate(getStr());
			}
			map.put("ok", true);
			break;
		case 7: // address
			c.setAddress(getStr());
			map.put("ok", true);
			break;
		case 8: // remark
			c.setRemark(getStr());
			map.put("ok", true);
			break;
		case 9: // followUp
			c.setFollowUp(getStr());
			map.put("ok", true);
			break;

		default:
			map.put("ok", false);
			map.put("err", "修改失败，未获取到switch case值！");
			break;
		}

		customerService.updateCustomer(c);

		JSONObject jsonObject = JSONObject.fromObject(map);
		jsonStr = jsonObject.toString();

		// 添加response响应头
		crossDomain();
		// return "listContact";
		return "json";
	}

	/**
	 * 获取编辑学生页面
	 * 
	 * @return
	 */
	@Action("editUICustomer")
	public String editUICustomer() {
		DetachedCriteria uCriteria = DetachedCriteria.forClass(User.class);
		affiliatedTeachers = customerService.findAllAffiliatedTeacher(uCriteria);

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject jsonCustomer;

		if (customer.getStudentId() == null) {
			map.put("ok", false);
			map.put("err", "请选择要修改的学生");

			jsonCustomer = JSONObject.fromObject(map);
			jsonStr = jsonCustomer.toString();

			// 添加response响应头
			crossDomain();
			return "json";
		}

		// 根据id查询要编辑的学生信息
		Customer c = customerService.findCustomerById(customer.getStudentId());

		// 把查询出来的对象压入栈顶
		ActionContext.getContext().getValueStack().push(c);

		map.put("studentId", c.getStudentId());
		map.put("studentName", c.getStudentName());
		map.put("studentSex", c.getStudentSex());
		map.put("studentAge", c.getStudentAge());
		map.put("phone1", c.getPhone1());
		map.put("phone2", c.getPhone2());
		map.put("followUp", c.getFollowUp());
		map.put("nextDate", c.getNextDate());
		map.put("address", c.getAddress());
		map.put("remark", c.getRemark());
		map.put("affiliatedTeacher", c.getAffiliatedTeacher().getUserName());

		jsonCustomer = JSONObject.fromObject(map);
		String strCustomer = jsonCustomer.toString();

		int j = affiliatedTeachers.size();
		String[] userArr = new String[j];

		if (affiliatedTeachers != null) {

			for (int i = 0; i < j; i++) {

				Map<String, Object> mapUser = new HashMap<String, Object>();

				User value = affiliatedTeachers.get(i);

				mapUser.put("userId", value.getUserId());
				mapUser.put("userName", value.getUserName());

				JSONObject jsonObject = JSONObject.fromObject(mapUser);
				userArr[i] = jsonObject.toString();
			}
		}

		String userStr = Arrays.toString(userArr);
		jsonStr = "{\"ok\": true,\r\n" + "\"orders\": " + strCustomer + ",\r\n \"users\": " + userStr + "}";

		// 添加response响应头
		crossDomain();
		return "json";
		// return "editUI";
	}

	/**
	 * 删除学生
	 * 
	 * @return
	 */
	@Action("removeCustomer")
	public String removeCustomer() {

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject jsonCustomer;

		if (customer.getStudentId() == null) {
			map.put("ok", false);
			map.put("err", "请选择要删除的学生");

			jsonCustomer = JSONObject.fromObject(map);
			jsonStr = jsonCustomer.toString();

			// 添加response响应头
			crossDomain();
			return "json";
		}

		customerService.removeCustomer(customer.getStudentId());

		map.put("ok", true);
		jsonCustomer = JSONObject.fromObject(map);
		jsonStr = jsonCustomer.toString();

		// 添加response响应头
		crossDomain();
		return "json";
		// return "listCustomer";
	}

	/**
	 * 批量删除
	 * 
	 * @return
	 */
	@Action("deleteAll")
	public String deleteAll() {
		String strCheckTnum = getCheckTnum();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject jsonCustomer;

		if (strCheckTnum == null || strCheckTnum.trim().equals("")) {
			map.put("ok", false);
			map.put("err", "请选择要删除的学生");

			jsonCustomer = JSONObject.fromObject(map);
			jsonStr = jsonCustomer.toString();

			// 添加response响应头
			crossDomain();
			return "json";
		}

		String[] checkedNums = strCheckTnum.split(",");
		int n = checkedNums.length;
		int[] checked = new int[n];

		for (int i = 0; i < n; i++) {

			checked[i] = Integer.parseInt(checkedNums[i]);
			customerService.deleteAll(checked[i]);
		}

		map.put("ok", true);
		jsonCustomer = JSONObject.fromObject(map);
		jsonStr = jsonCustomer.toString();

		// 添加response响应头
		crossDomain();
		return "json";
		// return "listCustomer";
	}

	/**
	 * 批量拉入公海
	 * 
	 * @return
	 */
	@Action("putCommonAll")
	public String putCommonAll() {

		String strCheckTnum = getCheckTnum();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject jsonCustomer;

		if (strCheckTnum == null || strCheckTnum.trim().equals("")) {
			map.put("ok", false);
			map.put("err", "请选择要拉入公海的学生");

			jsonCustomer = JSONObject.fromObject(map);
			jsonStr = jsonCustomer.toString();

			// 添加response响应头
			crossDomain();
			return "json";
		}

		String[] checkedNums = strCheckTnum.split(",");
		int n = checkedNums.length;
		int[] checked = new int[n];

		for (int i = 0; i < n; i++) {

			checked[i] = Integer.parseInt(checkedNums[i]);
			customerService.putCustomer(checked[i]);
		}

		map.put("ok", true);
		jsonCustomer = JSONObject.fromObject(map);
		jsonStr = jsonCustomer.toString();

		// 添加response响应头
		crossDomain();
		return "json";
		// return "listCustomer";
	}

	/**
	 * 新增学生
	 * 
	 * @return
	 */
	@Action("addCustomer")
	public String addCustomer() {

		User uSession = (User) ServletActionContext.getRequest().getSession().getAttribute("user");
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject jsonCustomer;

		// 将下次联系时间设置为" "
		/*
		 * User u = customer.getAffiliatedTeacher(); int uId = u.getUserId(); if (uId ==
		 * 0) { customer.setNextDate(""); }
		 */

		if (customer.getStudentName().trim().equals("") || customer.getStudentName() == null || customer == null) {
			map.put("ok", false);
			map.put("err", "学生命名名不能为空！");
		} else {

			customer.setAffiliatedTeacher(uSession);

			if (customer.getNextDate() == null) {
				customer.setNextDate("");
			}
			if (customer.getStudentSex() == null) {
				customer.setStudentSex(0);
			}

			// 保存学生
			customerService.saveCustomer(customer);
			// 计算今日联系总人数
			calculationContactNumber(customer);

			map.put("ok", true);
		}
		jsonCustomer = JSONObject.fromObject(map);
		jsonStr = jsonCustomer.toString();

		// 添加response响应头
		crossDomain();
		return "json";
		// return "listCustomer";
	}

	/**
	 * 查询学生列表
	 * 
	 * @return
	 */
	@SuppressWarnings({ "unlikely-arg-type", "unused" })
	@Action("findAllCustomer")
	public String findAllCustomer() {
		// int pageNumber = 1 ;
		// 设置页面最大记录数
		// int pageSize = 10;

		// 1.定义离线对象
		DetachedCriteria dCriteria = DetachedCriteria.forClass(Customer.class);
		DetachedCriteria delCriteria = DetachedCriteria.forClass(Customer.class);
		DetachedCriteria uCriteria = DetachedCriteria.forClass(User.class);

		// 删除员工时，所属学生全部归为“公海”
		customers = customerService.findAllCustomer(delCriteria);
		for (int i = 0; i < customers.size(); i++) {
			Customer value = customers.get(i);
			if (value.getAffiliatedTeacher() == null) {
				int id = value.getStudentId();
				customerService.updateAffiliatedTeache(id);
			}
		}

		// 通过Session，获取userId
		User u = (User) ServletActionContext.getRequest().getSession().getAttribute("user");
		Integer id = u.getUserId();

		// 2.拼装查询条件
		// 判断是否输入查询条件
		if (StringUtils.isNotBlank(getSelect())) {

			if (getSelect().matches("[0-9]*")) {

				long l = Long.parseLong(getSelect());

				dCriteria.add(Restrictions.or(

					// Restrictions.eq("studentId", Integer.parseInt(getSelect()),
					Restrictions.sqlRestriction("{alias}.phone1 LIKE (?)", "%" + l + "%", StringType.INSTANCE),
					Restrictions.sqlRestriction("{alias}.phone2 LIKE (?)", "%" + l + "%", StringType.INSTANCE)));
			
			} else {
				// 模糊查询学生名称
				dCriteria.add(Restrictions.like("studentName", "%" + getSelect() + "%"));
			}
		}

		if (id == 1) {

			// 查询每个所属教师的学生信息
			if (customer.getAffiliatedTeacher() != null && customer.getAffiliatedTeacher().getUserId() != null
					&& !"".equals(customer.getAffiliatedTeacher().getUserId())) {

				dCriteria.add(Restrictions.eq("affiliatedTeacher.userId", customer.getAffiliatedTeacher().getUserId()));
			}

			// 剔除公海的学生
			dCriteria.add(Restrictions.ne("affiliatedTeacher.userId", 0));

		} else {

			// 添加条件：当前用户id
			dCriteria.add(Restrictions.eq("affiliatedTeacher.userId", id));
		}

		// 3.根据离线对象查询学生信息
		// customers = customerService.findAllCustomer(dCriteria);
		PageBean<Customer> pageBean = customerService.findAllCustomer(dCriteria, currentPage, pageSize);

		affiliatedTeachers = customerService.findAllAffiliatedTeacher(uCriteria);

		// Customer cus = new Customer();
		// Map<Integer, String> map =
		// pageBean.getData().stream().collect(Collectors.toMap(Customer::getStudentId ,
		// Customer::getStudentName));

		// Map<String, Object> customerMap = new HashMap<String, Object>();
		// JSONObject jsonCustomer;
		// String jsonStr;

		int j = pageBean.getData().size();
		String[] order = new String[j];

		if (pageBean.getData() != null) {

			for (int i = 0; i < j; i++) {

				Map<String, Object> map = new HashMap<String, Object>();

				Customer value = pageBean.getData().get(i);

				// 性别转换
				/*
				 * String sex = null; Object o; if(value.getStudentSex() == 0) { sex = "男";
				 * 
				 * }else if(value.getStudentSex() == 1) { sex = "女";
				 * 
				 * }else { sex = "";
				 * 
				 * } o = (Object) sex;
				 */

				map.put("studentId", value.getStudentId());
				map.put("studentName", value.getStudentName());
				// map.put( "sex" , o);
				map.put("studentSex", value.getStudentSex());
				map.put("studentAge", value.getStudentAge());
				map.put("phone1", value.getPhone1());
				map.put("phone2", value.getPhone2());
				map.put("followUp", value.getFollowUp());
				map.put("nextDate", value.getNextDate());
				map.put("address", value.getAddress());
				map.put("remark", value.getRemark());
				map.put("affiliatedTeacher", value.getAffiliatedTeacher().getUserName());

				JSONObject jsonObject = JSONObject.fromObject(map);
				order[i] = jsonObject.toString();
				// order[i] = map;
			}
		}

		String str = Arrays.toString(order);
		jsonStr = "{\"ok\": true,\r\n" + "\"studentCountNum\":" + pageBean.getTotalRecord() + ",\r\n" + "\"orders\": "
				+ str + "}";

		/*
		 * Map<String, Object> mapBoolean = new HashMap<String, Object>();
		 * mapBoolean.put("ok", true); JSONObject json;
		 */

		/*
		 * customerMap.put("orders", str); customerMap.put("ok", true);
		 */

		/*
		 * System.out.println("customerMap : "+customerMap);
		 * 
		 * jsonCustomer = JSONObject.fromObject(customerMap); jsonStr =
		 * jsonCustomer.toString();
		 */

		// 手动放入值栈
		ActionContext.getContext().getValueStack().set("pageBean", pageBean);

		// 添加response响应头
		crossDomain();
		// return "findAll";
		return "json";
	}

	/**
	 * 获取添加学生页面
	 * 
	 * @return
	 */
	@Action("addUICustomer")
	public String addUICustomer() {
		DetachedCriteria uCriteria = DetachedCriteria.forClass(User.class);
		affiliatedTeachers = customerService.findAllAffiliatedTeacher(uCriteria);
		return "addUI";
	}

	/**
	 * 今日联系学生列表
	 * 
	 * @return
	 */
	@SuppressWarnings("unlikely-arg-type")
	@Action("contact")
	public String contact() {

		// 设置页面最大记录数
		// int pageSize = 1;

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date = new Date();
		String strDate = sdf.format(date);

		// 1.定义离线对象
		DetachedCriteria dCriteria = DetachedCriteria.forClass(Customer.class);
		DetachedCriteria uCriteria = DetachedCriteria.forClass(User.class);

		User u = (User) ServletActionContext.getRequest().getSession().getAttribute("user");
		Integer id = u.getUserId();
		
		// 2.拼装查询条件
		// 判断是否输入查询条件
		if (StringUtils.isNotBlank(getSelect())) {

			if (getSelect().matches("[0-9]*")) {

				long l = Long.parseLong(getSelect());

				dCriteria.add(Restrictions.or(

					// Restrictions.eq("studentId", Integer.parseInt(getSelect()),
					Restrictions.sqlRestriction("{alias}.phone1 LIKE (?)", "%" + l + "%", StringType.INSTANCE),
					Restrictions.sqlRestriction("{alias}.phone2 LIKE (?)", "%" + l + "%", StringType.INSTANCE)));
			
			} else {
				// 模糊查询学生名称
				dCriteria.add(Restrictions.like("studentName", "%" + getSelect() + "%"));
			}
		}

		if (id == 1) {

			if (customer.getAffiliatedTeacher() != null && customer.getAffiliatedTeacher().getUserId() != null
					&& !"".equals(customer.getAffiliatedTeacher().getUserId())) {

				dCriteria.add(Restrictions.eq("affiliatedTeacher.userId", customer.getAffiliatedTeacher().getUserId()));
			}

		} else {

			dCriteria.add(Restrictions.eq("affiliatedTeacher.userId", id));
		}

		// 添加今日联系日期条件
		dCriteria.add(Restrictions.eq("nextDate", strDate));
		// 3.根据离线对象查询学生信息
		// customers = customerService.findAllCustomer(dCriteria);
		PageBean<Customer> pageBeanContact = customerService.findAllCustomer(dCriteria, currentPage, pageSize);
		affiliatedTeachers = customerService.findAllAffiliatedTeacher(uCriteria);

		// 计算今日联系总人数
		calculationContactNumber();

		// 手动放入值栈
		ActionContext.getContext().getValueStack().set("pageBeanContact", pageBeanContact);

		if (id == 1) {

			users = userService.findAllUser(uCriteria);

			int j = users.size();
			String[] json = new String[j - 1];

			int[] num = new int[j];

			if (users != null) {

				for (int i = 1; i < j; i++) {

					Map<String, Object> map = new HashMap<String, Object>();

					User value = users.get(i);

					// 查询未联系学生人数
					DetachedCriteria ddCriteria = DetachedCriteria.forClass(Customer.class);

					ddCriteria.add(Restrictions.eq("affiliatedTeacher.userId", value.getUserId()));
					// 添加今日联系日期条件
					ddCriteria.add(Restrictions.eq("nextDate", strDate));

					num[i] = customerService.findContactNum(ddCriteria);

					map.put("userId", value.getUserId());
					map.put("userName", value.getUserName());
					map.put("studentNum", value.getStudentNum());
					map.put("contactNum", num[i]);

					JSONObject jsonObject = JSONObject.fromObject(map);
					json[i - 1] = jsonObject.toString();
				}

			}

			String str = Arrays.toString(json);
			int countContactNum = contacts.get(0).getCountContact();

			jsonStr = "{\"ok\": true,\r\n" + "\"studentCountNum\":" + countContactNum + ",\r\n" + "\"orders\": " + str
					+ "}";

			// 添加response响应头
			crossDomain();
			return "json";
			// return "contactRoot";

		} else {

			int j = pageBeanContact.getData().size();
			String[] order = new String[j];

			if (pageBeanContact.getData() != null) {

				for (int i = 0; i < j; i++) {

					Map<String, Object> map = new HashMap<String, Object>();

					Customer value = pageBeanContact.getData().get(i);

					map.put("studentId", value.getStudentId());
					map.put("studentName", value.getStudentName());
					map.put("studentSex", value.getStudentSex());
					map.put("studentAge", value.getStudentAge());
					map.put("phone1", value.getPhone1());
					map.put("phone2", value.getPhone2());
					map.put("followUp", value.getFollowUp());
					map.put("nextDate", value.getNextDate());
					map.put("address", value.getAddress());
					map.put("remark", value.getRemark());
					map.put("affiliatedTeacher", value.getAffiliatedTeacher().getUserName());

					JSONObject jsonObject = JSONObject.fromObject(map);
					order[i] = jsonObject.toString();
				}
			}

			String str = Arrays.toString(order);
			jsonStr = "{\"ok\": true,\r\n" + "\"studentCountNum\":" + pageBeanContact.getTotalRecord() + ",\r\n"
					+ "\"orders\": " + str + "}";

			/*
			 * contactMap.put("orders", str); contactMap.put("ok", true);
			 * 
			 * jsonContact = JSONObject.fromObject(contactMap); jsonStr =
			 * jsonContact.toString();
			 */

			// 添加response响应头
			crossDomain();
			return "json";
			// return "contactfindall";
		}

	}

	/**
	 * 获取今日联系编辑页面
	 * 
	 * @return
	 */
	@Action("editUIcontact")
	public String editUIcontact() {
		DetachedCriteria uCriteria = DetachedCriteria.forClass(User.class);

		affiliatedTeachers = customerService.findAllAffiliatedTeacher(uCriteria);

		// 根据id查询要编辑的学生信息
		Customer c = customerService.findCustomerById(customer.getStudentId());

		// 把查询出来的对象压入栈顶
		ActionContext.getContext().getValueStack().push(c);

		return "editUIcontact";
	}

	/**
	 * 编辑今日联系
	 * 
	 * @return
	 */
	@Action("editcontact")
	public String editcontact() {

		// 将下次联系时间设置为" "
		User u = customer.getAffiliatedTeacher();
		int uId = u.getUserId();
		if (uId == 0) {
			customer.setNextDate("");
		}
		customerService.updateCustomer(customer);
		return "listContact";
	}

	/**
	 * 公海查询
	 * 
	 * @return
	 */
	@Action("common")
	public String findCommon() {

		// 设置页面最大记录数
		// int pageSize = 2;

		// 1.定义离线对象
		DetachedCriteria dCriteria = DetachedCriteria.forClass(Customer.class);
		DetachedCriteria uCriteria = DetachedCriteria.forClass(User.class);

		// 2.拼装查询条件
		// 判断是否输入查询条件
		if (StringUtils.isNotBlank(getSelect())) {

			if (getSelect().matches("[0-9]*")) {

				long l = Long.parseLong(getSelect());

				dCriteria.add(Restrictions.or(

					// Restrictions.eq("studentId", Integer.parseInt(getSelect()),
					Restrictions.sqlRestriction("{alias}.phone1 LIKE (?)", "%" + l + "%", StringType.INSTANCE),
					Restrictions.sqlRestriction("{alias}.phone2 LIKE (?)", "%" + l + "%", StringType.INSTANCE)));
			
			} else {
				// 模糊查询学生名称
				dCriteria.add(Restrictions.like("studentName", "%" + getSelect() + "%"));
			}
		}

		// 3.根据离线对象查询学生信息
		// 添加条件：公海id 0
		dCriteria.add(Restrictions.eq("affiliatedTeacher.userId", 0));
		// customers = customerService.findAllCustomer(dCriteria);
		PageBean<Customer> pageBeanCommon = customerService.findAllCustomer(dCriteria, currentPage, pageSize);

		affiliatedTeachers = customerService.findAllAffiliatedTeacher(uCriteria);

		// 手动放入值栈
		ActionContext.getContext().getValueStack().set("pageBeanCommon", pageBeanCommon);

		int j = pageBeanCommon.getData().size();
		String[] order = new String[j];

		if (pageBeanCommon.getData() != null) {

			for (int i = 0; i < j; i++) {

				Map<String, Object> map = new HashMap<String, Object>();

				Customer value = pageBeanCommon.getData().get(i);

				map.put("studentId", value.getStudentId());
				map.put("studentName", value.getStudentName());
				map.put("studentSex", value.getStudentSex());
				map.put("studentAge", value.getStudentAge());
				map.put("phone1", value.getPhone1());
				map.put("phone2", value.getPhone2());
				map.put("followUp", value.getFollowUp());
				map.put("nextDate", value.getNextDate());
				map.put("address", value.getAddress());
				map.put("remark", value.getRemark());
				map.put("affiliatedTeacher", value.getAffiliatedTeacher().getUserName());

				JSONObject jsonObject = JSONObject.fromObject(map);
				order[i] = jsonObject.toString();
			}

		}

		String str = Arrays.toString(order);
		jsonStr = "{\"ok\": true,\r\n" + "\"studentCountNum\":" + pageBeanCommon.getTotalRecord() + ",\r\n"
				+ "\"orders\": " + str + "}";

		/*
		 * commonMap.put("orders", str); commonMap.put("ok", true);
		 * jsonCommon = JSONObject.fromObject(commonMap); jsonStr = jsonCommon.toString();
		 */

		// 添加response响应头
		crossDomain();
		return "json";
		// return "findCommon";
	}

	/**
	 * 拉出公海
	 * 
	 * @return
	 */
	@Action("pullCommon")
	public String pullCommon() {
		customerService.pullCustomer(customer.getStudentId());
		return "pullCommon";
	}

	/**
	 * 批量拉出公海
	 * 
	 * @return
	 */
	@Action("pullCommonAll")
	public String pullCommonAll() {

		String strCheckTnum = getCheckTnum();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject jsonCustomer;

		if (strCheckTnum == null || strCheckTnum.trim().equals("")) {
			map.put("ok", false);
			map.put("err", "请选择要拉出公海的学生");

			jsonCustomer = JSONObject.fromObject(map);
			jsonStr = jsonCustomer.toString();

			// 添加response响应头
			crossDomain();
			return "json";
		}

		String[] checkedNums = strCheckTnum.split(",");
		int n = checkedNums.length;
		int[] checked = new int[n];

		for (int i = 0; i < n; i++) {

			checked[i] = Integer.parseInt(checkedNums[i]);
			// checked[i] = Character.getNumericValue(str.charAt(i));

			customerService.pullCustomer(checked[i]);
		}

		map.put("ok", true);
		jsonCustomer = JSONObject.fromObject(map);
		jsonStr = jsonCustomer.toString();

		// 添加response响应头
		crossDomain();
		return "json";
		// return "pullCommon";
	}

	/**
	 * 拉入公海
	 * 
	 * @return
	 */
	@Action("putCommon")
	public String putCommon() {
		customerService.putCustomer(customer.getStudentId());
		return "putCommon";
	}

	/**
	 * 计算今日联系总人数
	 */
	public void calculationContactNumber() {

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date = new Date();
		String strDate = sdf.format(date);

		DetachedCriteria dCriteria = DetachedCriteria.forClass(Customer.class);
		// 添加今日联系日期条件
		dCriteria.add(Restrictions.eq("nextDate", strDate));
		// 3.根据离线对象查询学生信息
		PageBean<Customer> pageBeanC = customerService.findAllCustomer(dCriteria, currentPage, pageSize);

		while (true) {
			List<Contact> t;
			t = contactService.findById(1);
			// contacts = contactService.findById(1);

			String dateget = t.get(0).getDate();

			if (dateget.equals(strDate)) {
				Integer totalRecord = pageBeanC.getTotalRecord();

				if (t.get(0).getCountContact() < totalRecord) {
					// Contact.countContact = totalRecord;

					contactService.updateContact(totalRecord);
				}
				break;
			} else {
				contactService.updateContact(strDate);
			}
		}
		contacts = contactService.findById(1);
	}

	/**
	 * 计算今日联系总人数 添加、编辑学生 使用 联系总人数 + 1 操作
	 */
	public void calculationContactNumber(Customer customer) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date = new Date();
		String strDate = sdf.format(date);

		if (customer.getNextDate().equals(strDate)) {
			contactService.updateContact();
		}
	}

	/**
	 * 联系总人数 - 1 防重复操作
	 * 
	 * @param customer
	 */
	private void calculationContactNumberReduce(Integer n, String cusdate) {

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date = new Date();
		String strDate = sdf.format(date);

		if (cusdate.equals(strDate)) {
			jdbcDao dao = new jdbcDao();
			boolean flag = dao.find(n, cusdate);

			if (flag) {
				contactService.updateReduce();
			}
		}
	}

	/**
	 * 添加response响应头 跨域
	 */
	public void crossDomain() {
		String origin = request.getHeader("Origin");

		response.setHeader("Access-Control-Allow-Origin", origin);
		response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
		response.setHeader("Access-Control-Allow-Credentials", "true");
		
	}

	public List<Customer> getCustomers() {
		return customers;
	}

	public void setCustomers(List<Customer> customers) {
		this.customers = customers;
	}

	public List<User> getAffiliatedTeachers() {
		return affiliatedTeachers;
	}

	public void setAffiliatedTeachers(List<User> affiliatedTeachers) {
		this.affiliatedTeachers = affiliatedTeachers;
	}

	public List<User> getUsers() {
		return users;
	}

	public void setUsers(List<User> users) {
		this.users = users;
	}

	public List<Contact> getContacts() {
		return contacts;
	}

	public void setContacts(List<Contact> contacts) {
		this.contacts = contacts;
	}

	public String getSelect() {
		return select;
	}

	public void setSelect(String select) {
		this.select = select;
	}

	public int getCountContact() {
		return countContact;
	}

	public void setCountContact(int countContact) {
		this.countContact = countContact;
	}

	public String getCheckTnum() {
		return checkTnum;
	}

	public void setCheckTnum(String checkTnum) {
		this.checkTnum = checkTnum;
	}

	public Customer getCustomer() {
		return customer;
	}

	public void setCustomer(Customer customer) {
		this.customer = customer;
	}

	public int getN() {
		return n;
	}

	public void setN(int n) {
		this.n = n;
	}

	public String getStr() {
		return str;
	}

	public void setStr(String str) {
		this.str = str;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public int getCurrentPage() {
		return currentPage;
	}

	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}

	@Override
	public void setServletResponse(HttpServletResponse response) {

		this.response = response;
	}

	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	public String getJsonStr() {
		return jsonStr;
	}

	public void setJsonStr(String jsonStr) {
		this.jsonStr = jsonStr;
	}

}
